# encoding=utf8

from flask_socketio import Namespace
from threading import Lock, Thread
import time
import random

thread_lock = Lock()
thread = None


def background_thread(io):
    """Example of how to send server generated events to clients."""
    users_to_json = ''
    while True:
        print(users_to_json)
        users_to_json = [{'name': '王腾' + str(random.randint(1, 100))}]
        time.sleep(0.5) # 每五秒发送一次
        io.emit('user_response', {'data': users_to_json})


class SocketIO(Namespace):

    def on_connect(self):
        global thread
        self.get_session()
        with thread_lock:
            if thread is None:
                thread = Thread(target=background_thread, args=(self, ))
                thread.start()
        print('conneted')

    def on_disconnect(self):
        print('disconnect')

    def on_message(self, data):
        print('message:' + data[data])
        self.emit('response', {'message': 'test'})
